from flask import Flask, jsonify, request, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_cors import CORS
import uuid

app = Flask(__name__, static_folder='./dist/static', template_folder='./dist')
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://vote:123456@localhost:3306/vote'
db = SQLAlchemy(app)
Migrate(app, db)
CORS(app)

class Team(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True, nullable=False)
    prj = db.Column(db.String(64), nullable=False)
    score = db.Column(db.Integer)
    vote = db.Column(db.Integer)

    def to_json(self):
        data = {
            'id': self.id,
            'name': self.name,
            'prj': self.prj,
            'score': self.score,
            'vote': self.vote
        }
        return data

    def __repr__(self):
        return '<Team %r>' % self.name


@app.route('/', methods=['GET'])
def index():
    return render_template('/static/index.html')

@app.route('/teams', methods=['GET', 'POST'])
def teams():
    res_obj = {'status': 'success'}
    if request.method == 'POST':
        post_data = request.get_json()
        add_team(post_data)
        res_obj['message'] = '添加团队成功！'
    if request.method == 'GET':
        items = Team.query.all()
        res_obj['teams'] = [item.to_json() for item in items]
    return jsonify(res_obj)

@app.route('/teams/<id>', methods=['PUT', 'DELETE'])
def team(id):
    res_obj = {'status': 'success'}
    if request.method == 'PUT':
        put_data = request.get_json()
        remove_team(id)
        add_team(put_data)
        res_obj['message'] = '修改团队成功！'
    if request.method == 'DELETE':
        remove_team(id)
        res_obj['message'] = '删除团队成功！'
    return jsonify(res_obj)

def add_team(json_data):
    t = Team(name=json_data.get('name'), prj=json_data.get('prj'),
        score=json_data.get('score'), vote=json_data.get('vote'))
    db.session.add(t)
    db.session.commit()
            

def remove_team(id):
    Team.query.filter_by(id=id).delete()
    db.session.commit()


@app.route('/votes/', methods=['GET', 'POST'])
def vote():
    res_obj = {'status': 'success'}
    if request.method == 'POST':
        name = request.get_json().get('name')
        if addVote(name):
            res_obj['message'] = '已投票！'
        else:
            res_obj['message'] = '团队不存在'
    if request.method == 'GET':
        items = Team.query.all()
        res_obj['votes'] =  [item.to_json() for item in items]
    return jsonify(res_obj)


def addVote(name):
    team = Team.query.filter_by(name=name).first()
    if team:
        team.vote += 1
        db.session.add(team)
        db.session.commit()
        return True
    else:
        return False

if __name__ == '__main__':
    app.run()

